﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Ledict.ConditionExtract.DAL;
using Ledict.ConditionExtract.Model;
using Ledict.Regex.BLL;
using Ledict.Utility.Model;
using Ledict.ConditionExtract.Common;

namespace Ledict.ConditionExtract.BLL
{
    /// <summary>
    /// 信息来源
    /// </summary>
    public class Express_SourceBLL 
    {
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        Express_SourceDAL dal = new Express_SourceDAL();

        public bool Exists(string ccId, string sourceId, string sourceParagraphId, string sourcetexttype = "", string purposeId = "")
        {
            return dal.Exists(ccId, sourceId, sourceParagraphId, sourcetexttype, purposeId);
        }

        public bool DelSysExpressSource(string ccId, string sourceId, string sourceParagraphId, string sourcetexttype, string purpose)
        {
            return dal.DelSysExpressSource(ccId, sourceId, sourceParagraphId, sourcetexttype, purpose);
        }

        //public bool Exists(string ccId, string sourceId, string sourceParagraphId, string sourcetexttype, string purposeId, string ccRegexInfoCode, string eiName)
        //{
        //    return dal.Exists(ccId, sourceId, sourceParagraphId, sourcetexttype, purposeId, ccRegexInfoCode, eiName);


        //}
        /// <summary>
        /// 是否存在该记录，通过用途ID
        /// </summary>
        public bool ExistsByPurposeId(string esPurposeId)
        {
            return dal.ExistsByPurposeId(esPurposeId);

        }
        public DataTable GetExpressSourceDt(string ccId, string sourceId, string sourceParagraphId, string esPurposeId = null, string sourceTextType = null)
        {
            return dal.GetExpressSourceDt(ccId, sourceId, sourceParagraphId, esPurposeId, sourceTextType);
        }
        public bool AddSource(Ledict.ConditionExtract.Model.SysExpressSource Model)
        {
            return dal.AddSource(Model);
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Ledict.ConditionExtract.Model.SysExpressSource Model)
        {
            return dal.Update(Model);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataTable GetSource(string ccId)
        {
            return dal.GetSource_new(ccId);
            //return dal.GetSource(CC_ID);
        }

        /// <summary>
        /// 获得相关来源信息
        /// </summary>
        public string GetRelationSource(string CC_RegexInfoCode, string ES_ID)
        {
            return dal.GetRelationSource(CC_RegexInfoCode, ES_ID);
        }

        public bool DeleteSource(string ES_ID)
        {
            return dal.DeleteSource(ES_ID);
        }

        public bool DeleteSourceByCC_ID(string CC_ID)
        {
            return dal.DeleteSourceByCC_ID(CC_ID);
        }

        /// <summary>
        /// 批量添加来源
        /// </summary>
        /// <param name="sysExpressSource">表达式数据源实体</param>
        /// <param name="ccNodeTypes">节点类型列表（需要在哪种类型节点中添加数据来源）</param>
        /// <returns>操作结果</returns>
        public bool BatchAddSource(SysExpressSource sysExpressSource, IList<int> ccNodeTypes)
        {
            //SYS_Express_Source,查询出需要的来源，改下面的四个字段和对应正则库的规则Reg_Info
            string sourceId = sysExpressSource.Source_ID; //Source_ID
            string sourceParagraphId = sysExpressSource.Source_ParagraphID; //Source_ParagraphID
            string sourceName = sysExpressSource.Source_Name; //Source_Name
            string sourceParagraphName = sysExpressSource.Source_ParagraphName; //Source_ParagraphName
            string ccRegexInfoCode = "";

            try
            {
                var expressgroupsituationbll = new ExpressGroupSituationBLL();
                var newid = new NewIDBLL();
                var regexbll = new AboutRegexBLL();

                //11是xml节点，12是xml属性,排除“属性”两字
                //根据父节点，获取其下面的所有子节点或属性
                DataTable caseCausedt = expressgroupsituationbll.GetCaseCauseAutoSource(sysExpressSource.CC_ID, ccNodeTypes);
                for (int i = 0; i < caseCausedt.Rows.Count; i++)
                {
                    if (!Exists(caseCausedt.Rows[i]["CC_ID"].ToString(), sourceId, sourceParagraphId)) //不存在
                    {
                        SysExpressSource model = new SysExpressSource
                        {
                            ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
                            CC_ID = caseCausedt.Rows[i]["CC_ID"].ToString(),
                            Source_ID = sourceId,
                            Source_Name = sourceName,
                            Source_ParagraphID = sourceParagraphId,
                            Source_ParagraphName = sourceParagraphName,
                            CC_RegexInfoCode = ccRegexInfoCode
                        };

                        if (ccRegexInfoCode == "")
                        {
                            #region  信息单元
                            Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                            nodeChild.EI_Name = caseCausedt.Rows[i]["CC_Name"].ToString();
                            nodeChild.EN_ID = "EI_ID1507221438500001";
                            nodeChild.EI_Remark = "";
                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                            regexbll.AddReg_InfoUnit(nodeChild);

                            model.CC_RegexInfoCode = nodeChild.EI_Code;
                            #endregion
                        }
                        //添加来源
                        AddSource(model);
                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                Log.ErrorLog(ex.Message);
                return false;

            }
        }
        /// <summary>
        /// 批量添加来源（目前采用此版本，同一节点添加的信息一样）
        /// </summary>
        /// <param name="parentCcId">父节点ID</param>
        /// <param name="sysExpressSources">表达式数据源实体列表</param>
        /// <param name="ccNodeTypes">节点类型列表（需要在哪种类型节点中添加数据来源）</param>
        /// <returns>操作结果</returns>
        public JsonMsg BatchAddSource(string parentCcId, IList<SysExpressSource> sysExpressSources, IList<int> ccNodeTypes)
        {
            if (sysExpressSources == null || !sysExpressSources.Any()) return new JsonMsg(true, "表达式数据源实体列表为空", null);


            //定义全局信息提示
            string msg = string.Empty;
            string msg_exist = string.Empty;
            var iSuccess = 0;
            var iFail = 0;
            //var iExist = 0;

            try
            {
                var expressgroupsituationbll = new ExpressGroupSituationBLL();
                var newid = new NewIDBLL();
                var regexbll = new AboutRegexBLL();


                //根据父节点，获取其下面的所有子节点或属性或其他类型
                DataTable caseCausedt = expressgroupsituationbll.GetCaseCauseAutoSource(parentCcId, ccNodeTypes, false);
                if (caseCausedt == null || caseCausedt.Rows.Count == 0) return new JsonMsg(true, "子节点为空", null);

                //循环子节点或属性或其他类型
                for (int i = 0; i < caseCausedt.Rows.Count; i++)
                {
                    string ccRegexInfoCode = "";

                    //var isFirst = true; //判断是否是第一次复制信息单元,如果是，则需要创建新的信息单元，如果否，则复制关系即可
                    //var commonCcRegexCode = string.Empty;
                    foreach (var item in sysExpressSources)
                    {
                        //指定节点的规则不存在
                        if (!Exists(caseCausedt.Rows[i]["CC_ID"].ToString(), item.Source_ID, item.Source_ParagraphID, item.Source_TextType, item.EsPurposeId))
                        {
                            SysExpressSource model = new SysExpressSource
                            {
                                ES_ID = newid.JudgeDoc_CreateID("SYS_Express_Source"),
                                CC_ID = caseCausedt.Rows[i]["CC_ID"].ToString(),
                                Source_ID = item.Source_ID,
                                Source_Name = item.Source_Name,
                                Source_ParagraphID = item.Source_ParagraphID,
                                Source_ParagraphName = item.Source_ParagraphName,
                                CC_RegexInfoCode = item.CC_RegexInfoCode,
                                EsPurposeId = item.EsPurposeId,
                                Source_TextType = item.Source_TextType,
                                //CopySourceId = item.CopySourceId,
                                //CopyEsPurposeId = item.CopyEsPurposeId,
                                //CopySourceParagraphId = item.CopySourceParagraphId
                                //IsCopyRegex = item.IsCopyRegex
                            };

                            //信息单元为空，则新添加信息单元
                            if (string.IsNullOrEmpty(model.CC_RegexInfoCode))
                            {
                                #region  信息单元
                                Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                nodeChild.EI_Name = caseCausedt.Rows[i]["CC_Name"].ToString();
                                nodeChild.EN_ID = "EI_ID1507221438500001";
                                nodeChild.EI_Remark = "";
                                nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                regexbll.AddReg_InfoUnit(nodeChild);

                                model.CC_RegexInfoCode = nodeChild.EI_Code;
                                //ccRegexInfoCode = nodeChild.EI_Code;
                                #endregion
                            }
                            else  //正则code不为空
                            {
                                //判断是否需要复制信息单元（不复制信息单元,则批量同时添加时，同一节点上的同时添加的信息单元是一致的）
                                if (string.IsNullOrEmpty(item.CopyEsPurposeId) &&
                                    string.IsNullOrEmpty(item.CopySourceId) &&
                                    string.IsNullOrEmpty(item.CopySourceParagraphId) &&
                                    string.IsNullOrEmpty(item.CopySourceTextType))
                                {
                                    if (string.IsNullOrEmpty(ccRegexInfoCode))
                                    {
                                        //上级节点的正则规则是无法复制的，所以不复制正则信息，需要新添加信息来源，并保证同一批在同一节点的正则是一样的 todo by zhangpeng 2016-12-14
                                        Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                        nodeChild.EI_Name = caseCausedt.Rows[i]["CC_Name"].ToString();
                                        nodeChild.EN_ID = "EI_ID1507221438500001";
                                        nodeChild.EI_Remark = "";
                                        nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                        nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                        regexbll.AddReg_InfoUnit(nodeChild);

                                        model.CC_RegexInfoCode = nodeChild.EI_Code;
                                        ccRegexInfoCode = nodeChild.EI_Code;
                                    }
                                    model.CC_RegexInfoCode = ccRegexInfoCode;
                                }
                                else  //复制信息单元
                                {
                                    var dt = GetExpressSourceDt(caseCausedt.Rows[i]["CC_ID"].ToString(), item.CopySourceId,
                                    item.CopySourceParagraphId, item.CopyEsPurposeId, item.CopySourceTextType);
                                    //查询需要复制的信息单元在该节点上是否存在指定的来源规则，如果存在，则复制关系，如果不存在，则新建信息单元
                                    if (dt != null && dt.Rows.Count > 0)
                                    {
                                        model.CC_RegexInfoCode = dt.Rows[0]["CC_RegexInfoCode"].ToString();
                                    }
                                    else  //不存在，则新建规则
                                    {
                                        if (string.IsNullOrEmpty(ccRegexInfoCode))
                                        {
                                            #region  信息单元
                                            Reg_InfoUnit nodeChild = new Reg_InfoUnit();
                                            nodeChild.EI_Name = caseCausedt.Rows[i]["CC_Name"].ToString();
                                            nodeChild.EN_ID = "EI_ID1507221438500001";
                                            nodeChild.EI_Remark = "";
                                            nodeChild.EI_ID = newid.CreateID("Reg_InfoUnit");
                                            nodeChild.EI_Code = nodeChild.EI_ID;//编号==ID 
                                            regexbll.AddReg_InfoUnit(nodeChild);

                                            model.CC_RegexInfoCode = nodeChild.EI_Code;
                                            ccRegexInfoCode = nodeChild.EI_Code;
                                        }
                                        model.CC_RegexInfoCode = ccRegexInfoCode;

                                        #endregion
                                    }
                                }


                            }
                            //添加来源
                            if (AddSource(model))
                            {
                                iSuccess++;
                            }
                            else
                            {
                                iFail++;
                            }
                        }
                        else
                        {
                            msg_exist += string.Format("{2}的{0}-用途为{1}的规则已存在\r\n", item.Source_Name + "-" + item.Source_ParagraphName, item.EsPurposeName, caseCausedt.Rows[i]["CC_Name"]);
                            iFail++;
                        }
                    }
                }
                Dictionary<string, string> dic = new Dictionary<string, string>
                {
                    {"iSuccess", iSuccess.ToString()},
                    {"iFail", iFail.ToString()},
                    {"msg_exist", msg_exist}
                };

                return new JsonMsg(true, null, dic);


            }
            catch (Exception ex)
            {
                Log.ErrorLog(ex.Message);
                return new JsonMsg(false, ex.Message, null);

            }


        }

        /// <summary>
        /// 根据CCID，获取对应节点的用途列表（去重）
        /// </summary>
        /// <param name="ccId">节点ID</param>
        /// <returns></returns>
        public DataTable GetPurposeDtByCcid(string ccId)
        {
            return dal.GetPurposeDtByCcid(ccId);
        }

        /// <summary>
        /// 根据CCID和用途ID，获取对应节点的用途列表
        /// </summary>
        /// <param name="ccId">节点ID</param>
        /// <param name="purposeId">用途ID</param>
        /// <returns></returns>
        public DataTable GetParagraphDtByCcidAndPurpose(string ccId, string purposeId)
        {
            return dal.GetParagraphDtByCcidAndPurpose(ccId, purposeId);
        }

        /// <summary>
        /// 获取expressSource数据
        /// </summary>
        /// <param name="ccId"></param>
        /// <returns></returns>
        public DataTable GetExpressSourceData(string ccId)
        {
            return dal.GetExpressSourceData(ccId);
        }

        /// <summary>
        /// 根据ccid从expressSource表中获取regexInfoCode
        /// </summary>
        /// <param name="ccId"></param>
        /// <returns></returns>
        public string GetRegexInfoCodeByExpressSource(string ccId)
        {
            return dal.GetRegexInfoCodeByExpressSource(ccId);
        }

        /// <summary>
        /// 获取SYS_Express_Source表结构
        /// </summary>
        /// <returns></returns>
        public DataTable GetExpressSourceTableStructs()
        {
            return dal.GetExpressSourceTableStructs();
        }

        /// <summary>
        ///  获取ccid所有子节点的regexInfoCode
        /// </summary>
        /// <returns></returns>
        public DataTable GetRegexInfoCodeByCCID(string ccID)
        {
            return dal.GetRegexInfoCodeByCCID(ccID);
        }

        /// <summary>
        ///  获取ccid所有子节点的regexInfoCode
        /// </summary>
        /// <returns></returns>
        public DataTable GetRegexInfoCodeByCCID(string ccID, string eSPurpose, string sourceParagraphID)
        {
            return dal.GetRegexInfoCodeByCCID(ccID, eSPurpose, sourceParagraphID);
        }

        /// <summary>
        /// 规则共用获取数据
        /// </summary>
        /// <param name="ccids"></param>
        /// <param name="sourceNames"></param>
        /// <returns></returns>
        public DataTable GetExpressData(string ccids, string sourceNames, string ccName)
        {
            return dal.GetExpressData(ccids, sourceNames, ccName);
        }


        /// <summary>
        /// 规则共用获取数据
        /// </summary>
        /// <param name="ccids"></param>
        /// <param name="sourceNames"></param>
        /// <returns></returns>
        public DataTable GetExpressDataPL(string ccids, string sourceNames)
        {
            return dal.GetExpressDataPL(ccids, sourceNames);
        }
        /// <summary>
        /// 修改公共规则
        /// </summary>
        /// <param name="eiID"></param>
        /// <param name="ccids"></param>
        /// <param name="sourceName"></param>
        /// <returns></returns>
        public bool UpdateDataByCC_ID(string eiID, string ccids, string sourceName)
        {
            return dal.UpdateDataByCC_ID(eiID, ccids, sourceName);
        }

        /// <summary>
        /// 修改公共规则为空
        /// </summary>
        /// <param name="eiID"></param>
        /// <param name="ccids"></param>
        /// <param name="sourceName"></param>
        /// <returns></returns>
        public bool UpdateDataByES_ID(string ES_ID)
        {
            return dal.UpdateDataByES_ID(ES_ID);
        }
    }
}
